Page({
  data: {
    isRegister: false,
    language: 'zh',
    email: '',
    password: '',
    registerEmail: ''
  },

  onLoad() {
    // Load saved language preference
    const savedLanguage = wx.getStorageSync('language') || 'zh';
    this.setData({
      language: savedLanguage
    });
  },

  toggleForm() {
    this.setData({
      isRegister: !this.data.isRegister
    });
  },

  toggleLanguage() {
    const newLanguage = this.data.language === 'zh' ? 'en' : 'zh';
    this.setData({
      language: newLanguage
    });
    
    // Save language preference
    wx.setStorageSync('language', newLanguage);
  },

  onEmailInput(e) {
    this.setData({
      email: e.detail.value
    });
  },

  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    });
  },

  onRegisterEmailInput(e) {
    this.setData({
      registerEmail: e.detail.value
    });
  },

  login() {
    // Simulate login validation
    const validEmail = '123@qq.com';
    const validPassword = '123';
    
    if (this.data.email === validEmail && this.data.password === validPassword) {
      // Login success
      const userInfo = {
        email: this.data.email,
        userId: 'user123'
      };
      
      wx.setStorageSync('userInfo', userInfo);
      const app = getApp();
      app.globalData.isLoggedIn = true;
      app.globalData.userInfo = userInfo;
      
      wx.showToast({
        title: this.data.language === 'zh' ? '登录成功' : 'Login successful',
        icon: 'success'
      });
      
      // Navigate to main page
      wx.switchTab({
        url: '/pages/index/index'
      });
    } else {
      wx.showToast({
        title: this.data.language === 'zh' ? '邮箱或密码错误' : 'Invalid email or password',
        icon: 'none'
      });
    }
  },

  register() {
    if (!this.data.registerEmail) {
      wx.showToast({
        title: this.data.language === 'zh' ? '请输入邮箱' : 'Please enter email',
        icon: 'none'
      });
      return;
    }
    
    // Simulate registration
    wx.showToast({
      title: this.data.language === 'zh' ? '注册成功' : 'Registration successful',
      icon: 'success'
    });
    
    // Switch to login form
    this.setData({
      isRegister: false,
      email: this.data.registerEmail
    });
  }
});